package io.renren.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import io.renren.dao.TApiDeployinfoDao;
import io.renren.entity.TApiDeployinfoEntity;
import io.renren.service.TApiDeployinfoService;
import io.renren.utils.MybatisRedisCache;
import io.renren.utils.RRException;



@Service("tApiDeployinfoService")
public class TApiDeployinfoServiceImpl implements TApiDeployinfoService {
	@Autowired
	private TApiDeployinfoDao tApiDeployinfoDao;
	@Autowired
	private MybatisRedisCache redisCache;
	private ObjectMapper mapper = new ObjectMapper();
	/**
	 * 启用
	 * @param tApiDeployinfo
	 */
	public void enable(TApiDeployinfoEntity tApiDeployinfo) {
		TApiDeployinfoEntity dbInfo = this.queryObject(tApiDeployinfo.getId());
		if(dbInfo.getStatus()!=null&&dbInfo.getStatus()==1) {
			return;
		}
		this.update(tApiDeployinfo);
		dbInfo = this.queryObject(tApiDeployinfo.getId());
		try {
			redisCache.putString(dbInfo.getIp(), mapper.writeValueAsString(dbInfo));
		} catch (Exception e) {
			throw new RRException("缓存路由信息失败，检查redis 是否可用", 500);
		}
	}
	
	/**
	 * 禁用
	 * @param tApiDeployinfo
	 */
	public void disable(TApiDeployinfoEntity tApiDeployinfo) {
		TApiDeployinfoEntity dbInfo = this.queryObject(tApiDeployinfo.getId());
		if(dbInfo.getStatus()!=null&&dbInfo.getStatus()==0) {
			return;
		}
		this.update(tApiDeployinfo);
		dbInfo = this.queryObject(tApiDeployinfo.getId());
		try {
			redisCache.putString(dbInfo.getIp(), mapper.writeValueAsString(dbInfo));
		} catch (Exception e) {
			throw new RRException("缓存路由信息失败，检查redis 是否可用", 500);
		}
	}
	
	/**
	 * ekb授权获取token
	 * @param tApiDeployinfo
	 */
	public Object auth(TApiDeployinfoEntity tApiDeployinfo) {
		TApiDeployinfoEntity dbInfo = this.queryObject(tApiDeployinfo.getId());
		
		this.update(tApiDeployinfo);
		dbInfo = this.queryObject(tApiDeployinfo.getId());
		try {
			redisCache.putString(dbInfo.getIp(), mapper.writeValueAsString(dbInfo));
		} catch (Exception e) {
			throw new RRException("缓存路由信息失败，检查redis 是否可用", 500);
		}
		return this.testservice(dbInfo);
	}
	
	/**
	 * 测试连接
	 */
	public Object testservice(Integer id) {
		TApiDeployinfoEntity dbInfo = this.queryObject(id);
		if(dbInfo.getStatus()==null||dbInfo.getStatus()==0) {
			throw new RRException("请启用后进行授权操作", 500);
		}
		return this.testservice(dbInfo);
	}
	@Value("${apiproxyurl}")
	private String apiProxyUrl;
	private static String CORP_INFO_URL = "api/openapi/v1/corporations";
	private Object testservice(TApiDeployinfoEntity tApiDeployinfo) {
		
		try {
			StringBuffer buffer=null;  
	        try{  
	        	URL url=new URL(apiProxyUrl+CORP_INFO_URL+"?realip="+tApiDeployinfo.getIp());  
		        HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
		        conn.setDoOutput(true);  
		        conn.setDoInput(true);  
		        conn.setRequestMethod("GET");  
		        conn.connect();  
		        /*//往服务器端写内容 也就是发起http请求需要带的参数  
		        if(null!=outputStr){  
		            OutputStream os=conn.getOutputStream();  
		            os.write(outputStr.getBytes("utf-8"));  
		            os.close();  
		        }  */
		          
		        //读取服务器端返回的内容  
		        InputStream is=conn.getInputStream();  
		        InputStreamReader isr=new InputStreamReader(is,"utf-8");  
		        BufferedReader br=new BufferedReader(isr);  
		        buffer=new StringBuffer();  
		        String line=null;  
		        while((line=br.readLine())!=null){  
		            buffer.append(line);  
		        }  
	        }catch(Exception e){  
	            e.printStackTrace();  
	        }  
	        String res = buffer.toString();
	        
	        if(res.indexOf("405")>=0) {
	        	JSONObject jsonObjec = JSON.parseObject(res);
	        	
	        	throw new RRException(jsonObjec.get("msg").toString(),500);
	        }
	        //处理 数据库状态
	        TApiDeployinfoEntity dbInfo = new TApiDeployinfoEntity();
	        dbInfo.setId(tApiDeployinfo.getId());
	        dbInfo.setTokenStatus(1);
	        this.update(dbInfo);
	        return buffer.toString();  
			
		} catch (Exception e) {
			if(e instanceof RRException)
				throw (RRException)e;
			throw new RRException(e.getMessage(),500);
		}
	}
	
	@Override
	public TApiDeployinfoEntity queryObject(Integer id){
		return tApiDeployinfoDao.queryObject(id);
	}
	
	@Override
	public List<TApiDeployinfoEntity> queryList(Map<String, Object> map){
		return tApiDeployinfoDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return tApiDeployinfoDao.queryTotal(map);
	}
	
	@Override
	public void save(TApiDeployinfoEntity tApiDeployinfo){
		tApiDeployinfoDao.save(tApiDeployinfo);
	}
	
	@Override
	public void update(TApiDeployinfoEntity tApiDeployinfo){
		tApiDeployinfoDao.update(tApiDeployinfo);
	}
	
	@Override
	public void delete(Integer id){
		tApiDeployinfoDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		tApiDeployinfoDao.deleteBatch(ids);
	}

	@Override
	public List<TApiDeployinfoEntity> queryAll() {
		return tApiDeployinfoDao.queryAll();
	}
	
}
